import React, { useState, useEffect } from 'react';
import {
    Table,
    Button,
    Form,
    Input,
    Select,
    Modal,
    message,
    Upload,
    Tag,
    Space
} from 'antd';
import { UploadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { adminAPI } from '../services/api';
import * as XLSX from 'xlsx';

const { Option } = Select;

const RoomManagement = () => {
    const [rooms, setRooms] = useState([]);
    const [form] = Form.useForm();
    const [editForm] = Form.useForm();

    const [importModalVisible, setImportModalVisible] = useState(false);
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [editingRoom, setEditingRoom] = useState(null);

    const [fileList, setFileList] = useState([]);
    const [previewData, setPreviewData] = useState([]);
    const [importLoading, setImportLoading] = useState(false);
    const [tableLoading, setTableLoading] = useState(false);

    const [searchQuery, setSearchQuery] = useState('');

    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const [roomToDeleteId, setRoomToDeleteId] = useState(null);
    const [roomToDeleteInfo, setRoomToDeleteInfo] = useState(null);
    const [deleteLoading, setDeleteLoading] = useState(false);


    useEffect(() => {
        fetchRooms();
    }, []);

    const fetchRooms = async () => {
        setTableLoading(true);
        try {
            const { data } = await adminAPI.getAllRooms();
            // Sort rooms by room_number numerically
            const sortedRooms = data.sort((a, b) => {
                const roomNumA = parseInt(a.room_number, 10);
                const roomNumB = parseInt(b.room_number, 10);
                return roomNumA - roomNumB;
            });
            setRooms(sortedRooms);
        } catch (error) {
            console.error('获取房间列表失败:', error);
            message.error('获取房间列表失败');
        } finally {
            setTableLoading(false);
        }
    };

    const onFinish = async (values) => {
        try {
            await adminAPI.addRoom(values);
            message.success('房间添加成功');
            form.resetFields();
            fetchRooms();
        } catch (error) {
            console.error('添加房间失败:', error);
            message.error(error.response?.data?.message || '添加房间失败');
        }
    };

    const handleExcelFileUpload = (file) => {
        setImportLoading(true);
        const reader = new FileReader();

        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];

                const json = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false });

                if (json.length === 0) {
                    message.error('文件内容为空或格式不正确！');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                const headers = json[0];
                let rows = json.slice(1);

                const requiredHeaders = ['房间号', '房间类型', '床位数', '价格'];
                const trimmedHeaders = headers.map(h => typeof h === 'string' ? h.trim() : h);

                const isHeaderValid = requiredHeaders.every((val, index) => trimmedHeaders[index] === val);

                if (!isHeaderValid || headers.length !== requiredHeaders.length) {
                    message.error('Excel 文件标题行不符合要求！请确保是 "房间号, 房间类型, 床位数, 价格"。');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                rows = rows.filter(row => {
                    return row[0] !== undefined && row[0] !== null && String(row[0]).trim() !== '';
                });

                if (rows.length === 0) {
                    message.error('文件中没有有效的房间数据可供导入！');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                const formattedPreview = rows.map((row, index) => {
                    return {
                        key: `preview-${index}`,
                        room_number: String(row[0] || '').trim(),
                        room_type: String(row[1] || '').trim(),
                        beds: parseInt(row[2], 10) || 0,
                        price: parseFloat(row[3]) || 0.00,
                    };
                });

                const invalidData = formattedPreview.filter(item => (
                    !item.room_number ||
                    !item.room_type ||
                    isNaN(item.beds) || item.beds <= 0 ||
                    isNaN(item.price) || item.price < 0
                ));

                if (invalidData.length > 0) {
                    message.warn(`部分导入数据格式不正确（共 ${invalidData.length} 条），请检查预览数据！`);
                }

                setPreviewData(formattedPreview);
                setFileList([file]);
                message.success(`${file.name} 文件读取成功，请预览并点击“确定”开始导入！`);
            } catch (error) {
                console.error('解析Excel文件失败:', error);
                message.error('文件解析失败，请检查文件格式。');
                setPreviewData([]);
                setFileList([]);
            } finally {
                setImportLoading(false);
            }
        };

        reader.onerror = () => {
            message.error('文件读取失败！');
            setImportLoading(false);
        };

        reader.readAsArrayBuffer(file);
        return false;
    };

    const handleStartBulkImport = async () => {
        if (previewData.length === 0) {
            message.warn('没有数据可以导入！请先选择并解析Excel文件。');
            return;
        }

        setImportLoading(true);
        try {
            const importData = previewData.map(item => ({
                room_number: item.room_number,
                room_type: item.room_type,
                beds: item.beds,
                price: item.price,
            }));

            const response = await adminAPI.bulkImportRooms(importData);
            message.success(response.message || `成功导入 ${response.importedCount || 0} 个房间！`);
            setPreviewData([]);
            setFileList([]);
            setImportModalVisible(false);
            fetchRooms();
        } catch (error) {
            console.error('批量导入失败:', error);
            message.error(error.response?.data?.message || error.response?.data?.error || '房间批量导入失败！');
        } finally {
            setImportLoading(false);
        }
    };

    const handleEdit = (record) => {
        setEditingRoom(record);
        setEditModalVisible(true);
        setTimeout(() => {
            editForm.setFieldsValue({
                room_number: record.room_number,
                room_type: record.room_type,
                beds: record.beds,
                price: record.price,
                status: record.status,
            });
        }, 0);
    };

    const handleUpdateRoom = async (values) => {
        if (!editingRoom) return;

        try {
            await adminAPI.updateRoom(editingRoom.room_id, values);
            message.success('房间信息更新成功');
            setEditModalVisible(false);
            setEditingRoom(null);
            fetchRooms();
        } catch (error) {
            console.error('更新房间失败:', error);
            message.error(error.response?.data?.message || '更新房间失败');
        }
    };

    const handleDelete = (record) => {
        console.log('触发删除确认，房间信息:', record);
        setRoomToDeleteId(record.room_id);
        setRoomToDeleteInfo(record);
        setIsDeleteModalVisible(true);
    };

    const handleConfirmDelete = async () => {
        if (!roomToDeleteId) return;

        setDeleteLoading(true);
        console.log('用户确认删除，正在发送删除请求，房间ID:', roomToDeleteId);
        try {
            const response = await adminAPI.deleteRoom(roomToDeleteId);
            console.log('删除请求响应:', response);
            message.success('房间删除成功');
            fetchRooms();
            setIsDeleteModalVisible(false);
            setRoomToDeleteId(null);
            setRoomToDeleteInfo(null);
        } catch (error) {
            console.error('删除房间失败:', error);
            message.error(error.response?.data?.message || error.response?.data?.error || '删除房间失败');
        } finally {
            setDeleteLoading(false);
        }
    };

    const handleCancelDelete = () => {
        console.log('用户取消删除');
        setIsDeleteModalVisible(false);
        setRoomToDeleteId(null);
        setRoomToDeleteInfo(null);
    };


    const statusColor = {
        '空闲': 'green',
        '已入住': 'blue',
        '维护中': 'red'
    };

    const filteredRooms = rooms.filter(room =>
        room.room_number.includes(searchQuery) ||
        room.room_type.includes(searchQuery)
    );

    const columns = [
        { title: '房间号', dataIndex: 'room_number', key: 'room_number' },
        { title: '类型', dataIndex: 'room_type', key: 'room_type' },
        { title: '床位数', dataIndex: 'beds', key: 'beds' },
        { title: '价格', dataIndex: 'price', key: 'price', render: price => `¥${parseFloat(price).toFixed(2)}` },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: status => <Tag color={statusColor[status]}>{status}</Tag>
        },
        {
            title: '操作',
            key: 'actions',
            render: (text, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                        className="text-blue-500 hover:text-blue-700 transition-colors duration-200" // Tailwind classes for styling
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record)}
                        className="text-red-500 hover:text-red-700 transition-colors duration-200" // Tailwind classes for styling
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const previewColumns = [
        { title: '房间号', dataIndex: 'room_number', key: 'preview_room_number' },
        { title: '房间类型', dataIndex: 'room_type', key: 'preview_room_type' },
        { title: '床位数', dataIndex: 'beds', key: 'preview_beds' },
        { title: '价格', dataIndex: 'price', key: 'preview_price', render: price => `¥${parseFloat(price).toFixed(2)}` },
    ];

    return (
        // Main container with padding, background, and rounded corners
        <div className="min-h-screen bg-gray-100 p-6 font-inter antialiased">
            <div className="max-w-7xl mx-auto bg-white rounded-xl shadow-lg p-8">
                {/* Page Title */}
                <h1 className="text-4xl font-extrabold text-gray-800 mb-8 text-center">房间管理</h1>

                {/* Top Section: Bulk Import Button & Search Input */}
                <div className="flex flex-col md:flex-row justify-between items-center mb-8 space-y-4 md:space-y-0">
                    <Button
                        type="primary"
                        onClick={() => {
                            setImportModalVisible(true);
                            setFileList([]);
                            setPreviewData([]);
                        }}
                        icon={<PlusOutlined />}
                        className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105" // Enhanced button styling
                    >
                        批量导入房间
                    </Button>
                    <Input
                        placeholder="搜索房间号或房间类型"
                        prefix={<SearchOutlined className="text-gray-400" />} // Icon color
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full md:w-80 p-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 shadow-sm" // Input styling
                        allowClear
                    />
                </div>

                {/* Add New Room Section */}
                <h2 className="text-2xl font-bold text-gray-700 mb-5 border-b pb-3 border-gray-200">添加新房间</h2>
                <Form
                    form={form}
                    layout="inline"
                    onFinish={onFinish}
                    className="mb-10 p-6 border border-gray-200 rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 shadow-md flex flex-wrap gap-4 justify-center md:justify-start" // Enhanced form styling
                >
                    <Form.Item
                        name="room_number"
                        label={<span className="font-medium text-gray-700">房间号</span>}
                        rules={[{ required: true, message: '请输入房间号' }]}
                        className="flex-grow min-w-[150px]"
                    >
                        <Input placeholder="如: 101" className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                    </Form.Item>

                    <Form.Item
                        name="room_type"
                        label={<span className="font-medium text-gray-700">房间类型</span>}
                        rules={[{ required: true, message: '请选择房间类型' }]}
                        className="flex-grow min-w-[150px]"
                    >
                        <Select className="rounded-md" placeholder="选择类型">
                            <Option value="标准间">标准间</Option>
                            <Option value="大床房">大床房</Option>
                            <Option value="套房">套房</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="beds"
                        label={<span className="font-medium text-gray-700">床位数</span>}
                        rules={[{ required: true, message: '请输入床位数' }]}
                        className="flex-grow min-w-[100px]"
                    >
                        <Input type="number" min={1} className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                    </Form.Item>

                    <Form.Item
                        name="price"
                        label={<span className="font-medium text-gray-700">价格</span>}
                        rules={[{ required: true, message: '请输入价格' }]}
                        className="flex-grow min-w-[120px]"
                    >
                        <Input type="number" min={0} step={0.01} prefix="¥" className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                    </Form.Item>

                    <Form.Item className="flex-grow-0">
                        <Button
                            type="primary"
                            htmlType="submit"
                            icon={<PlusOutlined />}
                            className="bg-green-600 hover:bg-green-700 text-white font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105" // Enhanced button styling
                        >
                            添加房间
                        </Button>
                    </Form.Item>
                </Form>

                {/* All Rooms List Section */}
                <h2 className="text-2xl font-bold text-gray-700 mb-5 border-b pb-3 border-gray-200">所有房间列表</h2>
                <Table
                    dataSource={filteredRooms}
                    columns={columns}
                    rowKey="room_id"
                    bordered
                    loading={tableLoading}
                    pagination={{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }} // Enhanced pagination
                    className="rounded-lg shadow-md overflow-hidden" // Table styling
                />

                {/* Bulk Import Modal */}
                <Modal
                    title={<span className="text-xl font-semibold text-gray-800">批量导入房间</span>}
                    open={importModalVisible}
                    onOk={handleStartBulkImport}
                    onCancel={() => {
                        setImportModalVisible(false);
                        setFileList([]);
                        setPreviewData([]);
                    }}
                    okText="开始导入"
                    cancelText="取消"
                    confirmLoading={importLoading}
                    destroyOnClose={true}
                    width={800}
                    className="rounded-lg" // Modal styling
                >
                    <p className="mb-4 text-gray-700">请上传Excel文件（支持.xlsx, .xls格式）。</p>
                    <Upload
                        accept=".xlsx, .xls"
                        beforeUpload={handleExcelFileUpload}
                        fileList={fileList}
                        onRemove={() => { setFileList([]); setPreviewData([]); }}
                        maxCount={1}
                    >
                        <Button icon={<UploadOutlined />} className="bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-md shadow-sm">选择Excel文件</Button>
                    </Upload>
                    <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg text-gray-700 text-sm">
                        <p className="font-semibold mb-2">文件格式要求：</p>
                        <ul className="list-disc list-inside ml-4 space-y-1">
                            <li>文件格式: Excel (xlsx 或 xls)</li>
                            <li>第一个为标题行: "房间号", "房间类型", "床位数", "价格"</li>
                            <li>示例数据:</li>
                            <Table
                                dataSource={[
                                    { key: 'ex1', room_number: '101', room_type: '标准间', beds: 2, price: 300.00 },
                                    { key: 'ex2', room_number: '102', room_type: '大床房', beds: 1, price: 350.00 },
                                ]}
                                columns={previewColumns}
                                pagination={false}
                                size="small"
                                className="w-full mb-2 border border-blue-300 rounded-md" // Table styling
                                bordered
                            />
                        </ul>
                    </div>

                    {previewData.length > 0 && (
                        <h2 className="mt-8 text-lg font-semibold text-gray-700">预览数据 (共 {previewData.length} 条)</h2>
                    )}
                    <Table
                        columns={previewColumns}
                        dataSource={previewData}
                        pagination={{ pageSize: 5 }}
                        bordered
                        size="small"
                        className="mt-4 rounded-lg shadow-sm" // Table styling
                    />
                </Modal>

                {/* Edit Room Modal */}
                <Modal
                    title={<span className="text-xl font-semibold text-gray-800">编辑房间信息</span>}
                    open={editModalVisible}
                    onOk={() => editForm.submit()}
                    onCancel={() => {
                        setEditModalVisible(false);
                        setEditingRoom(null);
                        editForm.resetFields();
                    }}
                    okText="保存"
                    cancelText="取消"
                    destroyOnClose={true}
                    className="rounded-lg" // Modal styling
                >
                    <Form
                        form={editForm}
                        layout="vertical"
                        onFinish={handleUpdateRoom}
                        initialValues={editingRoom}
                    >
                        <Form.Item
                            name="room_number"
                            label={<span className="font-medium text-gray-700">房间号</span>}
                            rules={[{ required: true, message: '请输入房间号' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>

                        <Form.Item
                            name="room_type"
                            label={<span className="font-medium text-gray-700">房间类型</span>}
                            rules={[{ required: true, message: '请选择房间类型' }]}
                        >
                            <Select className="rounded-md" placeholder="选择类型">
                                <Option value="标准间">标准间</Option>
                                <Option value="大床房">大床房</Option>
                                <Option value="套房">套房</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            name="beds"
                            label={<span className="font-medium text-gray-700">床位数</span>}
                            rules={[{ required: true, message: '请输入床位数' }]}
                        >
                            <Input type="number" min={1} className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>

                        <Form.Item
                            name="price"
                            label={<span className="font-medium text-gray-700">价格</span>}
                            rules={[{ required: true, message: '请输入价格' }]}
                        >
                            <Input type="number" min={0} step={0.01} prefix="¥" className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>

                        <Form.Item
                            name="status"
                            label={<span className="font-medium text-gray-700">房间状态</span>}
                            rules={[{ required: true, message: '请选择房间状态' }]}
                        >
                            <Select className="rounded-md" placeholder="选择状态">
                                <Option value="空闲">空闲</Option>
                                <Option value="已入住">已入住</Option>
                                <Option value="维护中">维护中</Option>
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>

                {/* Custom Delete Confirmation Modal */}
                <Modal
                    title={<span className="text-xl font-semibold text-gray-800">确认删除</span>}
                    open={isDeleteModalVisible}
                    onOk={handleConfirmDelete}
                    onCancel={handleCancelDelete}
                    okText="确认"
                    cancelText="取消"
                    confirmLoading={deleteLoading}
                    destroyOnClose={true}
                    wrapClassName="delete-modal-wrapper" // Keep the z-index fix class
                    className="rounded-lg" // Modal styling
                >
                    <p className="text-gray-700 text-lg mb-2">您确定要删除房间 <span className="font-bold text-red-600">**{roomToDeleteInfo?.room_number}**</span> ({roomToDeleteInfo?.room_type}) 吗？此操作不可逆！</p>
                    <p className="text-sm text-gray-500">（房间ID: {roomToDeleteId}）</p>
                </Modal>
            </div>
        </div>
    );
};

export default RoomManagement;
